<template>
  <div>
    <!-- 工单管理表单弹窗 -->
    <el-dialog
      v-model="visibleDialog"
      :close-on-click-modal="false"
      :title="props.title"
      width="95%"
      draggable
      @close="closeDialog"
      modal-class="work-dialog"
      align-center
      style="min-width: 1350px; max-width: 1500px"
    >
      <el-tabs type="border-card">
        <el-tab-pane label="基本信息" style="height: 100%; min-height: 300px">
          <div class="flex" style="height: 100%">
            <div
              class="w-[790px]"
              style="
                border-right: 1px dashed black;
                padding-right: 14px;
                height: 100%;
                overflow-y: auto;
              "
            >
              <el-form
                ref="formRef"
                v-show="!props.isReadonly"
                :model="formData"
                :rules="rules"
                label-width="106"
              >
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="工段" prop="">
                      <el-input
                        v-model="formData.workshopSectionCode"
                        placeholder=""
                        disabled
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="工序" prop="processCode">
                      <el-input
                        v-model="formData.processCode"
                        placeholder=""
                        disabled
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="生产线" prop="equipName">
                      <el-input
                        v-model="formData.equipName"
                        placeholder=""
                        disabled
                      />
                    </el-form-item>
                  </el-col>
                  <!-- <el-col :span="8">
                    <el-form-item label="项目描述" prop="projectName">
                      <el-input
                        v-model="formData.projectName"
                        placeholder=""
                        disabled
                      />
                    </el-form-item>
                  </el-col> -->
                </el-row>
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="型号描述" prop="">
                      <el-input
                        v-model="formData.modelName"
                        placeholder=""
                        disabled
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="产品型号" prop="modelCode">
                      <el-input
                        v-model="formData.modelCode"
                        placeholder=""
                        disabled
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="监控分类" prop="abilityType">
                      <el-input
                        v-model="formData.abilityType"
                        placeholder=""
                        :formatter="
                          () =>
                            useDictionary(
                              'AbilityTypeMin',
                              formData.abilityType
                            )
                        "
                        disabled
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24" class="input2">
                    <el-form-item label="特性名称" prop="paramName">
                      <el-input
                        v-model="formData.paramName"
                        placeholder=""
                        disabled
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="公差上限" prop="upperLimitValue">
                      <el-input
                        v-model="formData.upperLimitValue"
                        placeholder=""
                        disabled
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item
                      label="控制线上限收严比例"
                      prop="controlRatioUp"
                      label-width="150px"
                    >
                      <el-input
                        v-model="formData.controlRatioUp"
                        placeholder=""
                        disabled
                        :suffixIcon="() => '%'"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="控制线上限" prop="controlUp">
                      <el-input
                        v-model="formData.controlUp"
                        placeholder=""
                        disabled
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="公差下限" prop="lowerLimitValue">
                      <el-input
                        v-model="formData.lowerLimitValue"
                        placeholder=""
                        disabled
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item
                      label="控制线下限收严比例"
                      prop="controlRatioDown"
                      label-width="150px"
                    >
                      <el-input
                        v-model="formData.controlRatioDown"
                        placeholder=""
                        disabled
                        :suffixIcon="() => '%'"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="控制线下限" prop="controlDown">
                      <el-input
                        v-model="formData.controlDown"
                        placeholder=""
                        disabled
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="8">
                    <el-form-item label="参考值" prop="nominal">
                      <el-input
                        v-model="formData.nominal"
                        placeholder=""
                        disabled
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="8">
                    <el-form-item label="测量值" prop="paramValue">
                      <el-input
                        v-model="formData.paramValue"
                        placeholder=""
                        disabled
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="责任人" prop="responsiblePersonName">
                      <el-input
                        v-model="formData.responsiblePersonName"
                        placeholder=""
                        disabled
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="工单状态" prop="workOrderStatus">
                      <el-input
                        v-model="formData.workOrderStatus"
                        placeholder="请输入工单状态"
                        :formatter="
                          () =>
                            useDictionary(
                              'PsmOrderStatus',
                              formData.workOrderStatus
                            )
                        "
                        disabled
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="8">
                    <el-form-item label="工单生成时间" prop="createTime">
                      <el-input
                        v-model="formData.createTime"
                        placeholder="请输入工单生成时间"
                        disabled
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="8">
                    <el-form-item label="最近处理时间" prop="lastUpdateTime">
                      <el-input
                        v-model="formData.lastUpdateTime"
                        placeholder="请输入最近处理时间"
                        disabled
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="监控描述" prop="workInfo">
                      <el-input
                        v-model="formData.workInfo"
                        placeholder=""
                        clearable
                        disabled
                        type="textarea"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="24"
                    ><el-form-item label="上传文件/图片">
                      <CommonUploadFile
                        accept=".doc,.docx,.pdf,.txt,.xlsx,.ppt,.mp4,.jpg,.png,.jpeg"
                        :isRead="props.isReadonly"
                        :files="formData.fileList || []"
                        :key="keyTime"
                        @update-files="updateFormFiles1"
                      /> </el-form-item
                  ></el-col>
                  <el-col :span="8"
                    ><el-form-item label="处理信息">
                      <el-button
                        type="primary"
                        @click="openInnerDialog(null, 1)"
                        >新增</el-button
                      >
                    </el-form-item></el-col
                  >

                  <el-col :span="24">
                    <el-form-item label="">
                      <el-table
                        :data="formData.orderProcessList"
                        border
                        style="width: 100%"
                      >
                        <el-table-column
                          prop="lastUpdatedUserName"
                          label="责任人"
                          width="80"
                          align="center"
                        />
                        <el-table-column
                          prop="measuresTime"
                          label="日期时间"
                          width="155"
                          align="center"
                        />
                        <el-table-column
                          prop="solutionMeasures"
                          label="解决措施"
                          align="left"
                          show-overflow-tooltip
                        />
                        <el-table-column
                          prop="completion"
                          label="完成度(%)"
                          width="90"
                          align="right"
                        />
                        <el-table-column label="操作" width="140" align="center"
                          ><template #default="scope">
                            <div>
                              <span
                                class="link"
                                @click="openInnerDialog(scope.row, 3)"
                                >查看</span
                              >
                              <span
                                class="link"
                                @click="openInnerDialog(scope.row, 2)"
                                >修改</span
                              >
                              <span
                                class="link red"
                                @click="deleteInner(scope.$index)"
                                >删除</span
                              >
                            </div>
                          </template>
                        </el-table-column>
                      </el-table>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>

              <el-descriptions :column="3" border v-if="props.isReadonly">
                <el-descriptions-item :span="1">
                  <template #label>
                    <div class="cell-item">工段</div>
                  </template>
                  {{ formData.workshopSectionCode || "" }}
                </el-descriptions-item>
                <el-descriptions-item :span="1">
                  <template #label>
                    <div class="cell-item">工序</div>
                  </template>
                  {{ formData.processCode || "" }}
                </el-descriptions-item>
                <el-descriptions-item :span="1">
                  <template #label>
                    <div class="cell-item">生产线</div>
                  </template>
                  {{ formData.equipName || "" }}
                </el-descriptions-item>
                <!-- <el-descriptions-item :span="1">
                  <template #label>
                    <div class="cell-item">项目描述</div>
                  </template>
                  {{ formData.projectName || "" }}
                </el-descriptions-item> -->
                <el-descriptions-item :span="1">
                  <template #label>
                    <div class="cell-item">型号描述</div>
                  </template>
                  {{ formData.modelName || "" }}
                </el-descriptions-item>
                <el-descriptions-item :span="1">
                  <template #label>
                    <div class="cell-item">产品型号</div>
                  </template>
                  {{ formData.modelCode || "" }}
                </el-descriptions-item>
                <el-descriptions-item :span="2">
                  <template #label>
                    <div class="cell-item">监控分类</div>
                  </template>
                  {{ useDictionary("AbilityTypeMin", formData.abilityType) }}
                </el-descriptions-item>
                <el-descriptions-item :span="3">
                  <template #label>
                    <div class="cell-item">特性名称</div>
                  </template>
                  {{ formData.paramName || "" }}
                </el-descriptions-item>
                <el-descriptions-item :span="1">
                  <template #label>
                    <div class="cell-item">公差上限</div>
                  </template>
                  {{ formData.upperLimitValue || "" }}
                </el-descriptions-item>
                <el-descriptions-item :span="1">
                  <template #label>
                    <div class="cell-item">控制线上限收严比例</div>
                  </template>
                  {{
                    formData.controlRatioUp ? formData.controlRatioUp + "%" : ""
                  }}
                </el-descriptions-item>
                <el-descriptions-item :span="1">
                  <template #label>
                    <div class="cell-item">控制线上限</div>
                  </template>
                  {{ formData.controlUp || "" }}
                </el-descriptions-item>

                <el-descriptions-item :span="1">
                  <template #label>
                    <div class="cell-item">公差下限</div>
                  </template>
                  {{ formData.lowerLimitValue || "" }}
                </el-descriptions-item>
                <el-descriptions-item :span="1">
                  <template #label>
                    <div class="cell-item">控制线下限收严比例</div>
                  </template>
                  {{
                    formData.controlRatioDown
                      ? formData.controlRatioDown + "%"
                      : ""
                  }}
                </el-descriptions-item>
                <el-descriptions-item :span="1">
                  <template #label>
                    <div class="cell-item">控制线下限</div>
                  </template>
                  {{ formData.controlDown || "" }}
                </el-descriptions-item>

                <el-descriptions-item :span="1">
                  <template #label>
                    <div class="cell-item">参考值</div>
                  </template>
                  {{ formData.nominal || "" }}
                </el-descriptions-item>
                <el-descriptions-item :span="1">
                  <template #label>
                    <div class="cell-item">测量值</div>
                  </template>
                  {{ formData.paramValue || "" }}
                </el-descriptions-item>
                <el-descriptions-item :span="1">
                  <template #label>
                    <div class="cell-item">责任人</div>
                  </template>
                  {{ formData.responsiblePersonName }}
                </el-descriptions-item>
                <el-descriptions-item :span="1">
                  <template #label>
                    <div class="cell-item">工单状态</div>
                  </template>
                  {{
                    useDictionary("PsmOrderStatus", formData.workOrderStatus) ||
                    ""
                  }}
                </el-descriptions-item>
                <el-descriptions-item :span="1">
                  <template #label>
                    <div class="cell-item">工单生成时间</div>
                  </template>
                  {{ formData.createTime }}
                </el-descriptions-item>
                <el-descriptions-item :span="1">
                  <template #label>
                    <div class="cell-item">最近处理时间</div>
                  </template>
                  {{ formData.lastUpdateTime }}
                </el-descriptions-item>
                <el-descriptions-item :span="3">
                  <template #label>
                    <div
                      class="cell-item"
                      style="font-weight: normal; min-width: 100px"
                    >
                      监控描述
                    </div>
                  </template>
                  <span style="word-break: break-all; word-wrap: break-word">{{
                    formData.workInfo
                  }}</span>
                </el-descriptions-item>
                <el-descriptions-item :span="3">
                  <template #label>
                    <div
                      class="cell-item"
                      style="font-weight: normal; min-width: 100px"
                    >
                      上传文件/图片
                    </div>
                  </template>
                  <CommonUploadFile
                    :showText="false"
                    :isRead="props.isReadonly"
                    :files="formData.fileList || []"
                    :key="keyTime"
                    @update-files="updateFormFiles1"
                  />
                </el-descriptions-item>
              </el-descriptions>
              <div v-if="props.isReadonly">
                <p
                  class="text-[16px] c-[#333] mb-[8px]"
                  style="font-weight: 600"
                >
                  处理信息
                </p>
                <el-table
                  :data="formData.orderProcessList"
                  border
                  style="width: 100%"
                >
                  <el-table-column
                    prop="lastUpdatedUserName"
                    label="责任人"
                    width="80"
                    align="center"
                  />
                  <el-table-column
                    prop="measuresTime"
                    label="日期时间"
                    width="155"
                    align="center"
                  />
                  <el-table-column
                    prop="solutionMeasures"
                    label="措施描述"
                    align="left"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    prop="completion"
                    label="完成度(%)"
                    width="90"
                    align="right"
                  />
                  <el-table-column label="操作" width="130" align="center"
                    ><template #default="scope">
                      <div>
                        <span
                          class="link"
                          @click="openInnerDialog(scope.row, 3)"
                          >查看</span
                        >
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
            <div
              class="flex-1 ml-[14px] sort"
              style="height: 100%; min-height: 300px; overflow-y: auto"
            >
              <PsmParamMonitorOther
                v-if="formData.equipCode"
                ref="PsmParamRef3"
                type="3"
                :equipCode="formData.equipCode"
                :equipId="formData.equipId"
                :key="3"
                :alarmTime="formData.collectionTime"
                :recordCount="3"
                style="margin-bottom: 14px"
              />
              <PsmParamMonitorOther
                v-if="formData.equipCode"
                ref="PsmParamRef1"
                type="1"
                :equipCode="formData.equipCode"
                :key="1"
                :alarmTime="formData.collectionTime"
                :recordCount="2"
                style="margin-bottom: 14px"
              />
              <PsmParamMonitorOther
                v-if="formData.equipCode"
                ref="PsmParamRef2"
                type="2"
                :equipCode="formData.equipCode"
                :key="2"
                :alarmTime="formData.collectionTime"
                :recordCount="2"
                style="margin-bottom: 14px"
              />
              <!-- <PsmParamMonitorOther
                  v-if="formData.equipCode"
                  ref="PsmParamRef4"
                  type="4"
                  :equipCode="formData.equipCode"
                  :key="4"
                /> -->
              <PsmParamMonitorOther
                v-if="formData.equipCode"
                ref="PsmParamRef5"
                type="5"
                :equipCode="formData.equipCode"
                :processEquipCode="
                  formData.processEquipCode || formData.equipCode
                "
                :key="5"
                :alarmTime="formData.collectionTime"
                :recordCount="1"
              />
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="历史记录"
          ><div class="flex-1 ml-[20px] sort">
            <el-card shadow="never" :border="false">
              <div style="display: flex; position: relative">
                <el-timeline
                  v-if="operationRecordList && operationRecordList.length"
                  style="width: 100%"
                >
                  <el-timeline-item
                    v-for="(activity, index) in operationRecordList"
                    :key="activity.id"
                    :type="typeBack(activity)"
                    :icon="iconBack(activity)"
                    :size="'large'"
                    :timestamp="activity.lastUpdateTime"
                  >
                    <div
                      style="
                        width: 100%;
                        word-break: break-all;
                        display: flex;
                        flex-direction: column;
                      "
                    >
                      <span style="font-weight: 700; font-size: 14px">
                        {{ activity.processingUserName }}-
                        {{ activity.processingActionDescribe }}</span
                      >
                      <span> {{ activity.processingOpinion }}</span>
                    </div>
                  </el-timeline-item>
                </el-timeline>
                <div
                  v-if="!operationRecordList || !operationRecordList.length"
                  class="flex justify-center m-auto mb-7"
                >
                  <span class="">暂无操作历史</span>
                </div>
                <div
                  v-if="operationRecordList.length"
                  style="
                    font-weight: 700;
                    font-size: 14px;
                    color: #a36c51;
                    position: absolute;
                    left: -2px;
                    top: -36px;
                    cursor: pointer;
                    height: 30px;
                    width: 50px;
                  "
                  @click="showOperationRecord"
                >
                  <i-ep-sort /> 排序
                </div>
              </div>
            </el-card>
          </div></el-tab-pane
        >
      </el-tabs>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="
              !props.isReadonly &&
              formData.workOrderStatus === 0 &&
              formData.functions.includes('accept')
            "
            type="primary"
            :loading="loading"
            @click="accept"
            >接受工单
          </el-button>
          <el-button
            v-if="
              !props.isReadonly &&
              formData.workOrderStatus === 1 &&
              formData.functions.includes('close')
            "
            type="primary"
            :loading="loading"
            @click="close"
            >关闭工单
          </el-button>
          <el-button
            v-if="
              !props.isReadonly &&
              formData.workOrderStatus === 2 &&
              formData.functions.includes('approve')
            "
            type="primary"
            @click="approveHandle"
            >批 准
          </el-button>
          <el-button
            v-if="
              !props.isReadonly &&
              formData.workOrderStatus === 2 &&
              formData.functions.includes('reject')
            "
            type="danger"
            :loading="loading"
            @click="rejected"
            >驳 回
          </el-button>
          <el-button
            v-if="
              !props.isReadonly &&
              formData.workOrderStatus === 1 &&
              formData.functions.includes('upgrade')
            "
            type="danger"
            @click="updatedHandle"
            >升 级
          </el-button>
          <el-button
            v-if="
              !props.isReadonly &&
              formData.workOrderStatus === 1 &&
              formData.functions.includes('update')
            "
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定
          </el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
      <!-- 内部嵌套弹窗 -->
      <el-dialog
        v-model="innerVisible"
        width="500"
        :title="innerTitle"
        append-to-body
        :close-on-click-modal="false"
        align-center
        :rules="innerRules"
      >
        <!-- <span>This is the inner Dialog</span> -->
        <el-form
          ref="innerFormRef"
          label-position="left"
          label-width="auto"
          :model="currentInner"
          :rules="innerRules"
          style="width: 100%"
        >
          <el-form-item label="责任人" prop="lastUpdatedUserName">
            <el-input
              v-model="currentInner.lastUpdatedUserName"
              placeholder=""
              style="width: 100%"
              disabled
            />
          </el-form-item>
          <el-form-item label="日期时间" prop="measuresTime">
            <el-date-picker
              v-model="currentInner.measuresTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择措施时间"
              style="width: 100%"
              :disabled="currentType === 3"
            />
          </el-form-item>
          <el-form-item label="处理措施" prop="solutionMeasures">
            <el-input
              placeholder="请输入处理措施"
              v-model="currentInner.solutionMeasures"
              type="textarea"
              show-word-limit
              :rows="4"
              maxlength="250"
              :disabled="currentType === 3"
            />
          </el-form-item>
          <el-form-item label="完成度(%)" prop="completion">
            <el-input-number
              v-model="currentInner.completion"
              :min="0"
              :max="100"
              controls-position="right"
              :disabled="currentType === 3"
            >
              <template #suffix>
                <span>%</span>
              </template></el-input-number
            >
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="handleInnerSubmit"
              >确 定
            </el-button>
            <el-button @click="closeInnerDialog">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import PsmParamMonitorOther from "@/views/psm/common/psmParamMonitorOther.vue";
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { useDictionary } from "../../../../utils/useTable"; // 引入
import {
  MoreFilled,
  Check,
  RefreshRight,
  ChatLineSquare,
  Edit,
  EditPen,
} from "@element-plus/icons-vue";
import dayjs from "dayjs";
import { useUserStore } from "@/store/modules/user";

const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "PCMPSMWORKORDERADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;

    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

// 图片处理
function updateFormFiles(val: []) {
  formData.imageList = val;
}
function updateFormFiles1(val: []) {
  formData.fileList = val;
}

const rules = reactive<any>({
  version: [],
  orderNo: [],
  processId: [],
  processCode: [],
  equipId: [],
  equipCode: [],
  equipName: [],
  modelCode: [],
  programName: [],
  collectionTime: [],
  workOrderStatus: [],
  parameterId: [],
  parameterName: [],
  paramName: [],
  abilityType: [],
  paramValue: [],
  monitoringResult: [],
  monitoringResultText: [],
  nominal: [],
  lowerLimitValue: [],
  upperLimitValue: [],
  controlRatioDown: [],
  controlRatioUp: [],
  controlDown: [],
  controlUp: [],
  responseTime: [],
  processingTime: [],
  responsiblePersonId: [],
  responsiblePersonName: [],
  actualResponsiblePersonId: [],
  actualResponsiblePersonName: [],
  changeReason: [
    { max: 255, message: "长度不能超过255个字符", trigger: "blur" },
  ],
  workInfo: [{ max: 255, message: "长度不能超过255个字符", trigger: "blur" }],
  changeRequisition: [],
  enabled: [],
  deleted: [],
  remarks: [],
  createTime: [],
  createdUserId: [],
  createdUserName: [],
  lastUpdateTime: [],
  lastUpdatedUserId: [],
  lastUpdatedUserName: [],
  orderProcessList: [],
});

const formRef = ref(ElForm);

let formData = reactive<any>({
  id: "",
  version: "",
  orderNo: "",
  processId: "",
  processCode: "",
  workshopSectionCode: "",
  modelName: "",
  equipId: "",
  equipCode: "",
  equipName: "",
  modelCode: "",
  projectName: "",
  programName: "",
  collectionTime: "",
  workOrderStatus: "",
  parameterId: "",
  parameterName: "",
  paramName: "",
  abilityType: "",
  paramValue: "",
  monitoringResult: "",
  monitoringResultText: "",
  nominal: "",
  lowerLimitValue: "",
  upperLimitValue: "",
  controlRatioDown: "",
  controlRatioUp: "",
  controlDown: "",
  controlUp: "",
  responseTime: "",
  processingTime: "",
  responsiblePersonId: "",
  responsiblePersonName: "",
  actualResponsiblePersonId: "",
  actualResponsiblePersonName: "",
  changeReason: "",
  workInfo: "",
  changeRequisition: "",
  enabled: "",
  deleted: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  orderProcessList: [],
  imageList: [],
  fileList: [],
  functions: [],
});

const PsmParamRef1 = ref();
const PsmParamRef2 = ref();
const PsmParamRef3 = ref();
const PsmParamRef5 = ref();
function openOther() {
  PsmParamRef1.value?.openColSetting();
  PsmParamRef2.value?.openColSetting();
  PsmParamRef3.value?.openColSetting();
  PsmParamRef5.value?.openColSetting();
}

const keyTime = ref(dayjs().valueOf());
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        version,
        orderNo,
        processId,
        processCode,
        workshopSectionCode,
        modelName,
        equipId,
        equipCode,
        equipName,
        modelCode,
        projectName,
        programName,
        collectionTime,
        workOrderStatus,
        parameterId,
        parameterName,
        paramName,
        abilityType,
        paramValue,
        monitoringResult,
        monitoringResultText,
        nominal,
        lowerLimitValue,
        upperLimitValue,
        controlRatioDown,
        controlRatioUp,
        controlDown,
        controlUp,
        responseTime,
        processingTime,
        responsiblePersonId,
        responsiblePersonName,
        actualResponsiblePersonId,
        actualResponsiblePersonName,
        changeReason,
        workInfo,
        changeRequisition,
        enabled,
        deleted,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        orderProcessList,
        imageList,
        fileList,
        functions,
      } = newVal;
      Object.assign(formData, {
        id,
        version,
        orderNo,
        processId,
        processCode,
        workshopSectionCode,
        modelName,
        equipId,
        equipCode,
        equipName,
        modelCode,
        projectName,
        programName,
        collectionTime,
        workOrderStatus,
        parameterId,
        parameterName,
        paramName,
        abilityType,
        paramValue,
        monitoringResult,
        monitoringResultText,
        nominal,
        lowerLimitValue,
        upperLimitValue,
        controlRatioDown,
        controlRatioUp,
        controlDown,
        controlUp,
        responseTime,
        processingTime,
        responsiblePersonId,
        responsiblePersonName,
        actualResponsiblePersonId,
        actualResponsiblePersonName,
        changeReason,
        workInfo,
        changeRequisition,
        enabled,
        deleted,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        orderProcessList: orderProcessList || [],
        imageList: imageList ?? [],
        fileList: fileList ?? [],
        functions: functions ?? [],
      });
      console.log("imageList", imageList);
      keyTime.value = dayjs().valueOf();
      if (
        (formData.lowerLimitValue > formData.paramValue ||
          formData.upperLimitValue < formData.paramValue) &&
        formData.workOrderStatus === 1
      ) {
        // rules.changeRequisition.push({
        //   required: true,
        //   message: "请输入变更申请单",
        //   trigger: "blur",
        // });
      } else {
        rules.changeRequisition.length = 0;
      }
      rules.changeRequisition.push({
        max: 255,
        message: "长度不能超过255个字符",
        trigger: "blur",
      });
      operationRecord();

      getMeasureList();

      setTimeout(() => {
        openOther();
      }, 100);
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.orderNo = "";
  formData.processId = "";
  formData.processCode = "";
  formData.workshopSectionCode = "";
  formData.modelName = "";
  formData.equipId = "";
  formData.equipCode = "";
  formData.equipName = "";
  formData.modelCode = "";
  formData.projectName = "";
  formData.programName = "";
  formData.collectionTime = "";
  formData.workOrderStatus = "";
  formData.parameterId = "";
  formData.parameterName = "";
  formData.paramName = "";
  formData.abilityType = "";
  formData.paramValue = "";
  formData.monitoringResult = "";
  formData.monitoringResultText = "";
  formData.nominal = "";
  formData.lowerLimitValue = "";
  formData.upperLimitValue = "";
  formData.responseTime = "";
  formData.processingTime = "";
  formData.responsiblePersonId = "";
  formData.responsiblePersonName = "";
  formData.actualResponsiblePersonId = "";
  formData.actualResponsiblePersonName = "";
  formData.changeReason = "";
  formData.workInfo = "";
  formData.changeRequisition = "";
  formData.enabled = "";
  formData.deleted = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.orderProcessList = [];
  formData.imageList = [];
  formData.fileList = [];
}

const loading = ref(false);

/** 工单管理保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/dmpDosPcm/pcmworkorder/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

const accept = async () => {
  loading.value = true;
  await request({
    url: "/dmpDosPcm/pcmworkorder/accept",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  ElMessage.success(`接受成功`);
  closeDialog();
  emit("reset-table", formData.id);
};

const close = async () => {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      ElMessageBox.confirm("确定关闭此工单吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        buttonSize: "default",
        type: "warning",
      }).then(async () => {
        loading.value = true;
        await request({
          url: "/dmpDosPcm/pcmworkorder/close",
          method: "post",
          data: formData,
        }).finally(() => {
          loading.value = false;
        });
        ElMessage.success(`关闭成功`);
        closeDialog();
        emit("reset-table", formData.id);
      });
    }
  });
};

const rejected = async () => {
  ElMessageBox.confirm("确定驳回此工单吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    buttonSize: "default",
    type: "warning",
  }).then(async () => {
    loading.value = true;
    await request({
      url: "/dmpDosPcm/pcmworkorder/rejected",
      method: "post",
      data: formData,
    }).finally(() => {
      loading.value = false;
    });
    ElMessage.success(`驳回成功`);
    closeDialog();
    emit("reset-table", formData.id);
  });
};

const updatedHandle = async () => {
  ElMessageBox.confirm("确定升级此工单吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    buttonSize: "default",
    type: "warning",
  }).then(async () => {
    loading.value = true;
    await request({
      url: "/dmpDosPcm/pcmworkorder/upgrade",
      method: "post",
      data: formData,
    }).finally(() => {
      loading.value = false;
    });
    ElMessage.success(`升级成功`);
    closeDialog();
    emit("reset-table", formData.id);
  });
};

const approveHandle = async () => {
  ElMessageBox.confirm("确定批准此工单吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    buttonSize: "default",
    type: "warning",
  }).then(async () => {
    loading.value = true;
    await request({
      url: "/dmpDosPcm/pcmworkorder/approve",
      method: "post",
      data: formData,
    }).finally(() => {
      loading.value = false;
    });
    ElMessage.success(`批准成功`);
    closeDialog();
    emit("reset-table", formData.id);
  });
};

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

// 负责人
const userList = ref<any>([]);
const getUserList = async () => {
  await request({
    url: "/system/sysUser/getList",
    method: "post",
    data: { enabled: 1 },
  }).then((res) => {
    userList.value = res.data;
  });
};

const changeActualResponsiblePerson = (id) => {
  const find = userList.value.find((item) => item.id === id);
  formData.actualResponsiblePersonName = find.firstName;
};

// 操作记录列表
const operationRecordList = ref([]);
const operationRecord = async () => {
  await request({
    url: "dmpDosPcm/psmworkorderprocessingrecord/getList",
    method: "post",
    data: { processingInstanceId: formData.id },
  }).then((res) => {
    operationRecordList.value = res.data;
  });
};
// 返回图标
const iconBack = (data) => {
  if (data.processingAction == "create") {
    return ChatLineSquare;
  } else if (data.processingAction == "specified") {
    return EditPen;
  } else if (data.processingAction == "close") {
    return RefreshRight;
  } else if (data.processingAction == "accept") {
    return Check;
  } else {
    return "";
  }
};
// 返回类型
const typeBack = (data) => {
  if (data.processingAction == "create") {
    return "primary";
  } else if (data.processingAction == "specified") {
    return "warning";
  } else if (data.processingAction == "specified") {
    return "warning";
  } else if (data.processingAction == "close") {
    return "danger";
  } else if (data.processingAction == "accept") {
    return "success";
  } else {
    return "";
  }
};

// 排序
const showOperationRecord = () => {
  if (operationRecordList.value.length > 0) {
    operationRecordList.value.reverse();
  }
};

const innerVisible = ref(false);
const innerTitle = ref("");
const currentInner = ref<any>({});
const currentType = ref<any>();
const currentSingle = {
  lastUpdatedUserName: useUserStore().user.userName,
  measuresTime: "",
  completion: 0,
  solutionMeasures: "",
};

const innerRules = reactive<any>({
  solutionMeasures: [
    { required: true, message: "请输入处理措施", trigger: "blur" },
    { min: 1, max: 250, message: "长度不能超过250个字符", trigger: "blur" },
  ],
  completion: [
    {
      required: true,
      message: "请输入完成度",
      trigger: "change",
    },
  ],
  measuresTime: [
    {
      type: "date",
      required: true,
      message: "请选择措施时间",
      trigger: "change",
    },
  ],
});

const innerFormRef = ref();
function handleInnerSubmit() {
  if (!innerFormRef.value) return;
  innerFormRef.value.validate((valid: any) => {
    if (valid) {
      if (currentInner.value.id) {
        const currentIndex = formData.orderProcessList.findIndex(
          (item: any) => {
            return item.id === currentInner.value.id;
          }
        );
        formData.orderProcessList[currentIndex] = currentInner.value;
      } else if (currentInner.value.addId) {
        const currentIndex = formData.orderProcessList.findIndex(
          (item: any) => {
            return item.addId === currentInner.value.addId;
          }
        );
        formData.orderProcessList[currentIndex] = currentInner.value;
      } else {
        currentInner.value.addId = dayjs().valueOf();
        currentInner.value.lastUpdatedUserName = useUserStore().user.userName;
        formData.orderProcessList = [
          ...formData.orderProcessList,
          toRaw(currentInner.value),
        ];
      }
      innerVisible.value = false;
    } else {
      console.log("error submit!");
    }
  });
}

async function getMeasureList() {
  request({
    url: `/dmpDosPcm/pcmworkorder/getDetails`,
    method: "post",
    data: {
      id: formData.id,
    },
  })
    .then((data) => {
      formData.orderProcessList = data.data || [];
    })
    .catch((res) => {
      console.log(res);
    });
}

function deleteInner(index: number) {
  ElMessageBox.confirm("确认删除当前数据项?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    formData.orderProcessList.splice(index, 1);
  });
}

function closeInnerDialog() {
  innerVisible.value = false;
}

function openInnerDialog(item: any, type: number) {
  const text = type == 1 ? "新增" : type == 2 ? "编辑" : "查看";
  innerTitle.value = text + "处理进度";
  currentType.value = type;
  if (item) {
    currentInner.value = JSON.parse(JSON.stringify(item));
  } else {
    currentInner.value = JSON.parse(JSON.stringify(currentSingle));
  }
  innerVisible.value = true;
  setTimeout(() => {
    innerFormRef.value.clearValidate();
  }, 50);
}
onMounted(async () => {
  await getUserList();
});
</script>

<style lang="scss" scoped>
:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 108px;
  padding: 8px 8px;
  font-weight: 400;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 120px;
  padding: 8px 8px;
}
:deep(.work-dialog > :first-child > :first-child) {
  height: calc(100% - 60px);
  --el-disabled-text-color: #444;
}
:deep(.work-dialog .el-dialog__body) {
  padding: 20px;

  .el-tabs {
    height: 100%;
  }
  .el-tabs__content {
    // height: calc(100vh - 120px - 40px - 60px - 100px);
    height: calc(100% - 40px);
    // min-height: 400px;
    // overflow-y: auto;
  }
}
.link {
  margin: 0 5px;
  cursor: pointer;
  font-size: 13px;
  color: #409eff;
}
.red {
  color: #f56c6c !important;
}

:deep(.sort .el-card__body) {
  padding: 45px 5px 10px 10px !important;
}
:deep(.el-card) {
  border: none;
}

//修改placeholder提示文字颜色
:deep(input::-webkit-input-placeholder) {
  -webkit-text-fill-color: #a8abb2 !important;
}
</style>
